package com.kyrie.lib_sys.application.timeApplys.service.impl;

import com.kyrie.lib_sys.application.timeApplys.pojo.entity.TimeRecord;
import com.kyrie.lib_sys.application.timeApplys.pojo.entity.ValidationResult;
import com.kyrie.lib_sys.application.timeApplys.mapper.TimeRecordMapper;
import com.kyrie.lib_sys.application.timeApplys.service.TimeRecordService;
import com.kyrie.lib_sys.utils.learn.TimeDemo.TimeValidator;
import com.kyrie.lib_sys.utils.learn.TimeDemo.TimeValidatorss;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TimeRecordServiceImpl implements TimeRecordService {

    @Autowired
    private TimeRecordMapper timeRecordMapper;


    /**
     * 单个记录校验并保存
     * @param record
     * @return
     */
    @Override
    @Transactional
    public ValidationResult validateAndSave(TimeRecord record) {
        // 1. 校验单个记录内部时间顺序
        ValidationResult result = TimeValidatorss.validateSingleRecord(record);
        if (!result.isValid()) {
            return result;
        }

        // 2. 检查与已有记录的时间重叠
        List<TimeRecord> existingRecords = timeRecordMapper.findByEmployeeIdAndTimeRange(
                record.getEmployeeId(),
                record.getPrepareTime(),
                record.getCompleteTime()
        );

        if (!existingRecords.isEmpty()) {
            result.setValid(false);
            result.addError("与已有工作时间记录存在重叠");
            return result;
        }

        // 3. 保存记录
        timeRecordMapper.insert(record);
        result.setMessage("工作时间记录保存成功");
        return result;
    }

    /**
     * 批量校验
     * @param newRecords
     * @param employeeId
     * @return
     */
    @Override
    public ValidationResult validateBatchWithExisting(List<TimeRecord> newRecords, Long employeeId) {
        List<TimeRecord> existingRecords = timeRecordMapper.findByEmployeeId(employeeId);

        ValidationResult result = TimeValidator.validateRecords(newRecords, existingRecords);

        //保存记录
        timeRecordMapper.insertBatch(newRecords);

        return result;
    }



    /**
     * 获取员工所有记录
     * @param employeeId
     * @return
     */
    @Override
    public List<TimeRecord> getEmployeeRecords(Long employeeId) {
        return timeRecordMapper.findByEmployeeId(employeeId);
    }

}